package com.example.myapplication.ui.activity.question

import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.chad.library.adapter.base.loadmore.SimpleLoadMoreView
import com.example.myapplication.R
import com.example.myapplication.arouter.ARouterPath
import com.example.myapplication.bean.article.ArticleBean
import com.example.myapplication.dialog.OperationDialog
import com.example.myapplication.ui.adapter.ArticleAdapter
import com.kun.base.env.Env
import com.kun.base.ui.AbsBaseActivity
import com.scwang.smart.refresh.header.ClassicsHeader
import kotlinx.android.synthetic.main.fragment_home.*
import kotlinx.android.synthetic.main.toolbar_layout.*

/**
 *问答
 *
 * @author : Kun
 * @date : 2021/6/10
 * @time : 15:17
 */
@Route(path = ARouterPath.QUESTION)
class QuestionActivity : AbsBaseActivity() {
    private var index = 0
    private lateinit var articleAdapter: ArticleAdapter

    private lateinit var questionViewModel: QuestionViewModel

    override fun getLayoutId(): Int {
        return R.layout.activity_question
    }

    override fun initViewModel() {
        questionViewModel = getActivityScopeViewModel(QuestionViewModel::class.java)
        questionViewModel.questionRequest.questionResult.observe(this, Observer { t ->
            if (t.errorCode == 0) {
                if (t.data!!.curPage == 1) {
                    articleAdapter.setList(t.data!!.datas)
                } else {
                    articleAdapter.addData(t.data!!.datas)
                }
                if (t.data!!.curPage >= t.data!!.pageCount) {
                    articleAdapter.loadMoreModule.loadMoreEnd()
                } else {
                    articleAdapter.loadMoreModule.loadMoreComplete()
                }
            } else {
                articleAdapter.loadMoreModule.loadMoreComplete()
            }
            refresh_layout!!.finishRefresh()
        })

        initAddCollectArticle()
        initDelCollectArticle()
    }

    override fun initView() {
        iv_back.setOnClickListener { finish() }
        tv_title.text = getString(R.string.question_and_answer)

        refresh_layout!!.setRefreshHeader(ClassicsHeader(this))
        articleAdapter = ArticleAdapter(R.layout.item_article, null)
        articleAdapter.loadMoreModule.loadMoreView = SimpleLoadMoreView()

        recycler_view!!.layoutManager = LinearLayoutManager(this)
        recycler_view!!.adapter = articleAdapter

        articleAdapter.loadMoreModule.setOnLoadMoreListener {
            //加载更多
            index++
            getData()
        }
        refresh_layout!!.setOnRefreshListener {
            //刷新数据
            index = 0
            getData()
        }
        articleAdapter.setOnItemClickListener { _, _, position ->
            //文章点击
            val articleBean = articleAdapter.getItem(position)
            startToWeb(articleBean.link, articleBean.title)
        }

        articleAdapter.addChildClickViewIds(R.id.tv_author, R.id.view_collect)
        articleAdapter.setOnItemChildClickListener { _, childView, position ->
            val articleBean = articleAdapter.getItem(position)
            if (childView.id == R.id.view_collect) {
                if (articleBean.collect) {
                    questionViewModel.requestDelCollectArticle(articleBean.id)
                } else {
                    questionViewModel.requestAddCollectArticle(articleBean.id)
                }
            } else if (childView.id == R.id.tv_author) {
                ARouter.getInstance().build(ARouterPath.USER_SHARED)
                    .withInt("userId", articleBean.userId)
                    .withString("nickName", articleBean.shareUser)
                    .navigation()
            }
        }
        articleAdapter.setOnItemLongClickListener { _, _, position ->
            val articleBean = articleAdapter.getItem(position)
            showOperationDialog(articleBean)
            return@setOnItemLongClickListener true

        }

        getData()
    }

    private fun getData() {
        questionViewModel.requestQuestion(index)
    }

    /**
     * 收藏文章接口回调
     */
    private fun initAddCollectArticle() {
        questionViewModel.collectRequest.addArticleResult.observe(this, Observer { t ->
            if (t.errorCode == 0) {
                articleAdapter.let {
                    val list = it.data
                    for (i in list) {
                        if (t.data == i.id) {
                            i.collect = true
                        }
                    }
                    it.notifyDataSetChanged()
                }
            }
        })
    }

    /**
     * 取消收藏文章接口回调
     */
    private fun initDelCollectArticle() {
        questionViewModel.collectRequest.delArticleResult.observe(this, Observer { t ->
            if (t.errorCode == 0) {
                articleAdapter.let {
                    val list = it.data
                    for (i in list) {
                        if (t.data == i.id) {
                            i.collect = false
                        }
                    }
                    it.notifyDataSetChanged()
                }
            }
        })
    }

    /**
     * 跳转到web页面
     */
    private fun startToWeb(linkUrl: String, title: String) {
        var url = linkUrl
        if (!url.startsWith("http://") && !url.startsWith("https://")) {
            url = Env.getDomain() + url
        }

        ARouter.getInstance().build(ARouterPath.WEB).withString("url", url)
            .withString("title", title).navigation()
    }

    /**
     * 显示操作弹窗
     */
    private fun showOperationDialog(articleBean: ArticleBean) {
        OperationDialog(this).apply {
            addSelectItems("打开链接", if (articleBean.collect) "取消收藏" else "收藏")
            setOnSelectListener(object : OperationDialog.OnSelectListener {
                override fun onSelect(name: String, position: Int) {
                    if (position == 0) {
                        startToWeb(articleBean.link, articleBean.title)
                    } else {
                        if (articleBean.collect) {
                            questionViewModel.requestDelCollectArticle(articleBean.id)
                        } else {
                            questionViewModel.requestAddCollectArticle(articleBean.id)
                        }
                    }
                    dismiss()
                }
            })
        }.show()
    }
}